package com.service.impl;

import com.component.ErrorCode;
import com.dao.UserDao;
import com.exception.ExceptionCast;
import com.exception.ExceptionCatch;
import com.entity.User;
import com.service.UserService;
import com.util.IdWorkerUtil;
import com.util.JwtUtil;
import com.util.Sha256Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @ClassName UserServiceImpl
 * @Description 用户接口实现
 * @Author XiangQian
 * @Date 2022/7/7 9:32
 */

@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);
    @Autowired
    private UserDao userDao;
    @Resource
    private IdWorkerUtil idWorkerUtil;
    @Resource
    private JwtUtil jwtUtil;
    @Override
    public void insertUser(User user) {

        // 避免空指针异常 Optional、isPresent配套使用
        Optional<User> userInfo = Optional.ofNullable(userDao.selectAllByPhoneAndName(user));
        if (user.getName().isEmpty()) {
            LOGGER.error("账号为空");
            ExceptionCast.cast(ErrorCode.RegisterFail_ParamHasEmpty);
        }
        if (user.getPassword().isEmpty()) {
            LOGGER.error("密码为空");
            ExceptionCast.cast(ErrorCode.RegisterFail_ParamHasEmpty);
        }
        if (userInfo.isPresent()) {
            LOGGER.error("注册失败，该账户已经存在");
            ExceptionCast.cast(ErrorCode.RegisterFail_AccountHasExist);
        }
        // new time 进行调用
        LocalDateTime localDateTime = LocalDateTime.now();
        Timestamp timestamp = Timestamp.valueOf(localDateTime);
        user.setStatus(1);
        user.setCreateTime(timestamp);
        user.setLatestTime(timestamp);
        user.setId(idWorkerUtil.nextId());
        user.setPassword(Sha256Util.getSHA256(user.getPassword()));
        userDao.insert(user);

    }

    @Override
    public String selectUserByUserInfo(User user) {

        /**
         * QueryWrapper
         *查询用户是否存在
         */
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", user.getPhone());
        queryWrapper.eq("password", Sha256Util.getSHA256(user.getPassword()));
        queryWrapper.isNotNull("delete_time");
        queryWrapper.eq("status", 1);
        Optional<User> userInfo = Optional.ofNullable(userDao.selectOne(queryWrapper));
        if (user.getName().isEmpty()) {
            LOGGER.error("账号为空");
            ExceptionCast.cast(ErrorCode.RegisterFail_ParamHasEmpty);
        }
        if (user.getPassword().isEmpty()) {
            LOGGER.error("密码为空");
            ExceptionCast.cast(ErrorCode.RegisterFail_ParamHasEmpty);
        }
        if (!userInfo.isPresent()) {
            LOGGER.error("登陆失败，用户名或密码错误或已被禁用");
            ExceptionCast.cast(ErrorCode.LoginFail_ParamHasEmpty);
        }


        // Jwt令牌登陆验证使用
        User temp = userInfo.get();
        // 能够返回状态定义为20
        Map<String, Object> map = new HashMap<>(20);
        User jwtUserInfo = new User();
        jwtUserInfo.setId(temp.getId());
        jwtUserInfo.setName(temp.getName());
        jwtUserInfo.setEmail(temp.getEmail());
        jwtUserInfo.setStatus(temp.getStatus());
        return jwtUtil.createJwt(String.valueOf(temp.getId()), temp.getName(), map);

    }

    @Override
    public void stopUser(User user) {

        LocalDateTime localDateTime = LocalDateTime.now();
        Timestamp timestamp = Timestamp.valueOf(localDateTime);
        user.setLatestTime(timestamp);
        user.setStatus(2);
        if (userDao.updateById(user) == 0) {
            LOGGER.error("禁止失败，当前用户不存在");
            ExceptionCast.cast(ErrorCode.ProhibitUserFail_ResultIsZero);
        }
    }

    @Override
    public void deleteUser(User user) {

        LocalDateTime localDateTime = LocalDateTime.now();
        Timestamp timestamp = Timestamp.valueOf(localDateTime);
        user.setDeleteTime(timestamp);
        user.setLatestTime(timestamp);
        if (userDao.updateById(user) == 0){
            LOGGER.error("删除失败，用户不存在·或者已被删除");
            ExceptionCast.cast(ErrorCode.DeleteUserFail_ResultIsZero);
        }
    }
}
